(function($){
    var settings = {
        autoOpen: true,
        buttons: {},
        dataType: 'json',
        height: 'auto',
        modal: false,
        resizable: true,
        title: '',
        url: '',
        width: 300
    };

    var success_uploads_flag = false;
    var total_files_for_upload = 0;
    var counter_total = 0;
    var couner_upload = 0;
    var counter_fail = 0;

    var methods = {
        init: function(options) {
            return this.each(function() {
                if(options) {
                    $.extend(settings, options);
                }


                var upload_window_content = '<form class="prsfileupload" enctype="multipart/form-data" method="post">' +
                '<span class="fileinput-button">' +
                '<input type="file" name="files[]" multiple="" id="file-input-field" />' +
                '</span><input type="hidden" id="form-coordinate-system" name="coordinate_system" />' +
                '<input type="hidden" id="form-coordinate-koatuu" name="coordinate_system_koatuu" />' +
                '</form><div class="prsfileupload-list"></div>';

                var upload_list_template = '<div class="list-item">' +
                '<span class="item-filename"></span>' +
                '<span class="item-spinner"></span>' +
                '<span class="item-size"></span>' +
                '<span class="item-done-status"></span>' +
                '<span class="item-done-message"></span>' +
                '</div>';

                var counter_template = '<div class="counter">'+
                '<span class="label-counter-total">В черзі: </span><span class="counter-total"></span>' +
                '<span class="label-counter-upload">Завантажено: </span><span class="counter-upload"></span>' +
                '<span class="label-counter-fail">Не завантажено: </span><span class="counter-fail"></span>' +
                '</div>';

                $(this).empty();
                
                $(upload_window_content).appendTo(this);
                $(counter_template).appendTo(this);

                setUploadMessage();
                initCounter();                

                $(this).dialog({
                    autoOpen: settings.autoOpen,
                    resizable: settings.resizable,
                    buttons: settings.buttons,
                    height: settings.height,
                    modal: settings.modal,
                    title: settings.title,
                    width: settings.width,
                    close: function(event, ui) {
                        setUploadMessage();
                        initCounter();
                        if(success_uploads_flag) {
                            success_uploads_flag = false;
                            window.location.reload(true);
                        }
                    }
                });

                var prsfileupload = $('form.prsfileupload').fileupload({
                    dataType: settings.dataType,
                    url: settings.url
                });

                prsfileupload.bind('fileuploadsubmit', function (e, data) {
                    var prsfileupload_item = $(upload_list_template);
                    prsfileupload_item.find('.item-filename').html(data.files[0].name);
                    prsfileupload_item.appendTo("div.prsfileupload-list");
                    data.prsfileupload_item = prsfileupload_item;
                });

                prsfileupload.bind('fileuploaddone', function (e, data) {
                    data.prsfileupload_item.find('.item-spinner').remove();
                    data.prsfileupload_item.find('.item-size').remove();

                    if(data.result.success == true) {
                        success_uploads_flag = true;
                        data.prsfileupload_item.find('.item-done-status').addClass('item-done-status-ok');
                        data.prsfileupload_item.find('.item-done-message').text(data.result.msg);
                        counterUploadUp();
                    }else {
                        data.prsfileupload_item.find('.item-done-message').text(data.result.msg);
                        data.prsfileupload_item.find('.item-done-status').addClass('item-done-status-fail');
                        counterFailUp();
                    }
                });

                prsfileupload.bind('fileuploadfail', function (e, data) {
                    data.prsfileupload_item.find('.item-spinner').remove();
                    data.prsfileupload_item.find('.item-size').remove();
                    data.prsfileupload_item.find('.item-done-status').addClass('item-done-status-fail');
                    data.prsfileupload_item.find('.item-done-message').text("Не вдалося завантажити файл");
                    counterFailUp();
                });

                prsfileupload.bind('fileuploadprogress', function (e, data) {
                    if(data.lengthComputable) {
                        var progress_text = Math.round(data.loaded / data.total * 100) + '% із ' + formatSize(data.total);
                        data.prsfileupload_item.find('.item-size').html(progress_text);
                    }
                });

                prsfileupload.bind('fileuploadstop', function (e) {
                    uploadFinishMessage();
                });

                prsfileupload.fileupload('disable');

                $('#file-input-field').change(function (e) {
                    if(e.target.files.length <= 500) {
                        $('.prsfileupload-list').empty();
                        initCounter();
                        setCounter(e.target.files.length);

                        prsfileupload.fileupload('enable');
                        prsfileupload.fileupload('add', {
                            files: e.target.files || [{
                                name: this.value
                            }],
                            fileInput: $(this)
                        });
                        prsfileupload.fileupload('disable');
                    }else {
                        setUploadMessage();
                        simpleDialog("Кількість вибраних файлів перевищує 500 (пятьсот)", "Помилка");
                    }
                });

                preloadImages();

            });
        },
        close: function() {
            $(this).dialog("close");
        },
        open: function() {
            $(this).dialog("open");
        },
        select: function() {          
            $(".fileinput-button input").click();           
        }
    };

    var preloadImages = function() {
        pix=new Array("/images/loader.gif", "/images/upload-ok.png", "/images/upload-fail.png")
        pic=new Array()
        for(i=0;i<=pix.length-1;i++) {
            pic[i]=new Image()
            pic[i].src=pix[i]
        }
    }

    var initCounter = function() {
        total_files_for_upload = 0;
        counter_total = 0;
        couner_upload = 0;
        counter_fail = 0;
        $('span.counter-total').html(counter_total);
        $('span.counter-upload').html(couner_upload);
        $('span.counter-fail').html(counter_fail);
    }

    var setCounter = function(value) {
        total_files_for_upload = value;
        counter_total = value;
        $('span.counter-total').html(counter_total);
    }

    var counterUploadUp = function() {
        counter_total--;
        couner_upload++;
        $('span.counter-upload').html(couner_upload);
        $('span.counter-total').html(counter_total);
    }

    var counterFailUp = function() {
        counter_total--;
        counter_fail++;
        $('span.counter-fail').html(counter_fail);
        $('span.counter-total').html(counter_total);
    }

    var uploadFinishMessage = function() {
        var message = "<div style='padding-top: 20px;'>Загальна кількість файлів: <b>" + total_files_for_upload +
        "</b><br />Завантажено: <b>" + couner_upload +
        "</b><br />Не завантажено: <b>" + counter_fail +
        "</b></div>";
        $(message).dialog({
            modal: true,
            title: 'Файли завантажено',
            resizable: false,
            buttons: {
                "Закрити": function() {
                    $(this).dialog("close");
                }
            }
        });
    }

    var simpleDialog = function(message, title) {
        $("<div style='text-align: center; padding-top: 20px;'>" + message + "</div>").dialog({
            modal: true,
            title: title,
            resizable: false,
            buttons: {
                "Закрити": function() {
                    $(this).dialog("close");
                }
            }
        });
    }

    var setUploadMessage = function() {
        var upload_notice_content = '<div class="upload-notice">Кількість файлів для одного завантаження не має перевищувати 500 (пятьсот)</div>';
        $('.prsfileupload-list').empty();
        $('.prsfileupload-list').append(upload_notice_content);

    }

   

    var formatSize = function(bytes) {
        var i = -1;
        do {
            bytes = bytes / 1024;
            i++;
        } while (bytes > 99);

        return Math.max(bytes, 0.1).toFixed(1) + ['КБ', 'МБ', 'ГБ'][i];
    }

    $.fn.prsfileupload = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Метод ' +  method + ' не існує в jQuery.prsfileupload');
        }
    };
})(jQuery);
